package org.anlu.guava.utils;

import com.google.common.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * <p>
 * Description:TODO 详细描述
 * <p>
 * <p>
 *
 * @author anlu
 * @date 2024/1/9 11:34
 */
public class DataConverter {
    private Map<Type, Function<Object, ?>> converterMap = new HashMap<>();

    // 注册转换器
    public <T> void registerConverter(TypeToken<T> typeToken, Function<Object, T> converter) {
        converterMap.put(typeToken.getType(), converter);
    }

    // 执行转换
    public <T> T convert(Object input, TypeToken<T> targetTypeToken) {
        Function<Object, ?> converter = converterMap.get(targetTypeToken.getType());
        if (converter != null) {
            return (T) targetTypeToken.getRawType().cast(converter.apply(input));
        }
        throw new IllegalArgumentException("未找到合适的转换器");
    }


}
